<template>
  <div class="fieldsTemplateContainer">
    <div class="alert">
      项目字段管理用于配置项目需要的显示字段，配置完成后需和项目类型进行关联，配置后对后续使用该项目类型的项目生效。
    </div>
    <CToolbar
      :fields="dialogFields"
      :visibleButtons="toolbarOptions"
      :search-fields="['name']"
      @openAddRecordDialog="handleAddField"
      style="position: relative; top: 0; left: 0; padding: 8px 0"
    >
      <template #toolbar-right-before>
        <el-input
          v-model="searchName"
          placeholder="输入关键词"
          class="search-input"
          :prefix-icon="Search"
          @change="handleSearch"
          style="margin-right: 6px"
        />
      </template>
    </CToolbar>
    <div class="wbs-tree-container">
      <!--   表格   -->
      <CLTable
        v-loading="loading"
        :fields="tableFields"
        :initial-data="tableData"
        :line-height="currentLineHeight"
        :more-actions="moreActions"
        :tableConfig="tableConfig"
        :page-query="tableDataQuery"
        @pagerChange="pagerChange"
        @onMoreAction="handleMoreAction"
        @show:records="handleShowRecords"
      >
      </CLTable>
      <!-- 字段配置悬浮层 -->
      <FieldConfigPopup
        :fields="currentFields"
        :position="fieldConfigPosition"
        :visible="showFieldConfig"
        @close="showFieldConfig = false"
        @fieldsChange="handleFieldsChange"
      />
    </div>
    <CDialog
      :title="operate === 'create' ? '新建' : '编辑'"
      v-model="dialogVisible"
      @handleDialogOk="handleCreateOrEdit"
      :fields="dialogFields"
      :nodeData="selectedNode"
    ></CDialog>
  </div>
</template>
<script setup lang="ts">
  import { Search } from "@element-plus/icons-vue";
  import { ElInput, ElMessage, ElMessageBox } from "element-plus";
  import CToolbar from "@/components/CToolbar.vue";
  import { tableFields, dialogFields } from "./fields/index.ts";
  import { ref, provide, reactive, onMounted } from "vue";
  import FieldConfigPopup from "@/components/FieldConfigPopup.vue";
  import CLTable from "@/components/CLTable/index.vue";
  import type { DynamicField } from "@/data/wbsFields.ts";
  import type { pagerListQueryType } from "@/interface/common.ts";
  import CDialog from "@/components/CDialog.vue";
  import {
    getTemplateList,
    createTemplate,
    deleteTemplate,
    updateTemplate,
  } from "@/api/pm/customFieldTemplate.ts";
  import type { ColumnDefinedTemplateEntityRes } from "@/interface/pm/customFieldTemplate.ts";
  import { deepCopy } from "@/utils/common.ts";
  import { useRouter } from "vue-router";

  interface propsType {
    type: string;
  }
  const router = useRouter();
  const props = defineProps<propsType>();
  const dialogVisible = ref(false);
  const operate = ref("create");
  const searchName = ref("");
  const loading = ref(false);
  const handleSearch = () => {};
  // 工具栏选项
  const toolbarOptions = ref({
    add: {
      name: "新增",
      enable: true,
    },
    fieldConfig: false,
    filter: false,
    sort: false,
    lineHeight: false,
    help: false,
    log: false,
    export: false,
    search: false,
  });
  const handleAddField = () => {
    dialogVisible.value = true;
    operate.value = "create";
  };

  // 表格
  const tableDataQuery = reactive<pagerListQueryType>({
    pageNo: 1,
    pageSize: 10,
    conditions: [],
    total: 0,
    targetType: props.type,
  });
  const fields = ref<DynamicField[]>(tableFields); // table表格展示列
  const tableData = ref<ColumnDefinedTemplateEntityRes[]>([]);
  const selectedNode = ref<ColumnDefinedTemplateEntityRes>({});
  // 当前行高设置
  const currentLineHeight = ref<"low" | "medium" | "high" | "ultra-high">(
    "low",
  );
  const moreActions = ref([
    { key: "setting", label: "字段配置" },
    { key: "edit", label: "编辑" },
    { key: "delete", label: "删除" },
  ]);
  const tableConfig = ref({
    editable: false,
    borderMode: "none",
    tableH: "calc(100vh - 228px)",
    showOperationsColumn: true, // 是否显示操作列
    OperationsColumnMode: "textIcon", // 操作列模式，text为文本模式
    OperationsColumnWidth: 140, //自定义操作列宽度
    frozenColCount: 0, // 冻结前面列数
    rightFrozenColCount: 0, // 冻结后面列数
    page: {
      enable: true,
    },
    // tree: {
    //   enabled: true, // 开启树形结构
    //   column: 2, // 开启的树形结构的列索引
    //   mode: "wbs", // 开启wbs模式
    // },
    // rowSeriesNumber: {
    //   dragOrder: true, // 开启行号拖拽排序
    // },
    // borderMode: "none", // 表格边框模式，none为无边框
  });

  const pagerChange = (pager: { currentPage: number; pageSize: number }) => {
    tableDataQuery.pageNo = pager.currentPage;
    tableDataQuery.pageSize = pager.pageSize;
    getTableData();
  };
  const handleMoreAction = async (action: string, node: any) => {
    if (action === "edit") {
      dialogVisible.value = true;
      operate.value = "edit";
      selectedNode.value = deepCopy(node);
    } else if (action === "delete") {
      ElMessageBox.confirm(
        "确定要删除该项目字段模版么？删除后无法恢复，请谨慎操作。",
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          draggable: true,
        },
      )
        .then(async () => {
          await deleteTemplate(node.id);
          ElMessage({
            type: "success",
            message: "删除成功",
          });
          getTableData();
        })
        .catch(() => {});
    } else if (action === "setting") {
      router.push(
        `/pm/globalSetting/customFieldTemplateDetail?id=${node.id!}&name=${node.name}`,
      );
    }
  };
  const handleShowRecords = (records: any[]) => {
    console.log("handleShowRecords", records);
  };

  // 配置字段
  const currentFields = ref<DynamicField[]>([]);
  const fieldConfigPosition = ref({ left: 0, top: 0 });
  const showFieldConfig = ref(false);

  // 处理字段配置变化
  const handleFieldsChange = (updatedFields: DynamicField[]) => {
    // 更新本地字段配置，确保拖拽后能同步显示
    currentFields.value = JSON.parse(JSON.stringify(updatedFields));
    console.log("字段配置已更新:", updatedFields);
    fields.value = [...updatedFields];
  };

  // 显示字段配置弹窗
  const showFieldConfigPopup = (position: { left: number; top: number }) => {
    fieldConfigPosition.value = position;
    currentFields.value = JSON.parse(JSON.stringify(fields.value || []));
    setTimeout(() => {
      showFieldConfig.value = !showFieldConfig.value;
    }, 100);
  };
  // const addRecord = (newRecords: ProjectNode[]) => {
  //   tableData.value = [...newRecords];
  // };
  //
  // // 提供给所有子孙组件使用
  // provide("addRecord", addRecord);
  provide("showFieldConfigPopup", showFieldConfigPopup);

  const getTableData = async () => {
    loading.value = true;
    const res = await getTemplateList(tableDataQuery);
    loading.value = false;
    tableDataQuery.total = res.total;
    tableData.value =
      res.result?.map((item) => {
        item.count = item.count + "";
        return item;
      }) || [];
  };

  const handleCreateOrEdit = async (formData: any) => {
    if (operate.value === "create") {
      await createTemplate({ name: formData.name, targetType: props.type });
      ElMessage({
        type: "success",
        message: "新建成功",
      });
      dialogVisible.value = false;
      getTableData();
    } else if (operate.value === "edit") {
      await updateTemplate({
        name: formData.name,
        id: formData.id,
        targetType: props.type,
      });
      ElMessage({
        type: "success",
        message: "编辑成功",
      });
      dialogVisible.value = false;
      getTableData();
    }
  };

  onMounted(() => {
    getTableData();
  });
</script>

<style scoped lang="scss">
  .fieldsTemplateContainer {
    padding: 8px 8px 0 8px;
    .alert {
      height: 32px;
      background: #fff3eb;
      display: flex;
      align-items: center;
      color: #5e5e5e;
      font-size: 14px;
      padding: 0 12px;
      margin-bottom: 14px;
    }
    .wbs-tree-container {
      background-color: #fff;
      position: relative;
      .table-container {
        margin-top: 8px;
        height: calc(100vh - 200px);
      }
    }
  }
</style>
